package com.nuanshui.heatedloan.socket.msg.handler;

import io.netty.channel.ChannelHandlerContext;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.heatedloan.annotation.MsgHandler;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.socket.ProtoMsg.Msg;
import com.nuanshui.heatedloan.socket.client.ClientManager;
import com.nuanshui.heatedloan.socket.client.TcpUser;
import com.nuanshui.heatedloan.socket.msg.MsgIdType;
import com.nuanshui.heatedloan.socket.server.TCPServer;
import com.nuanshui.heatedloan.userinfo.facade.UserTokenService;
import com.nuanshui.heatedloan.userinfo.tool.UserTool;


/**
 * 用户登录消息处理类
 * @author GH
 *
 */
@MsgHandler(MsgIdType.CLIENT_LOGIN_MSG)
public class ClientLoginMsgHandler implements IHandler,InitializingBean {

	private Logger logger  = LoggerFactory.getLogger(ClientLoginMsgHandler.class);
		
	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
    private UserTokenService userTokenService;

	@Override
	public void doHandle(Msg m, ChannelHandlerContext ctx) {
			
		try {
			logger.info("登录消息: "+m.getSafeToken()+"  "+m.getUserId());
			String userId = m.getUserId();
			String safeToken = m.getSafeToken();
			if(StringUtils.isNotEmpty(userId) && StringUtils.isNotEmpty(safeToken)) {//用户id 和safeToken都存在
				if(userTokenService.validSafeToken(safeToken)) {//表示safeToken是合法的
					TcpUser tcpUser = new TcpUser();
					tcpUser.setUserId(userId);
					tcpUser.setSafeToken(safeToken);
					ClientManager.addClient(ctx, tcpUser);
					TCPServer.getSingletonInstance().send(m.toBuilder(), ctx);
				}
				
			}	
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	@Override
	public void afterPropertiesSet() throws Exception {
		
		
	}

}
